package com.fyzk.activity.dialog;

import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.adapter.PhaseListAdapter;
import com.fyzk.bean.BetResponse;
import com.fyzk.bean.SeniorPhaseItem;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.SureDialog;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.L;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.ASView;
import com.fyzk.view.TopTitleView;
import com.fyzk.view.ViewCallBack;
import com.fyzk.view.ViewCallBack.CountDownInterface;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;


@ContentView(R.layout.seniorchasebet_activity)
public class SeniorZhuiHaoActivity extends BaseActivity implements CountDownInterface, ASView
        .OnValueChangedLisener {

    @ViewInject(R.id.seniorchase_top)
    private TopTitleView seniorchase_top;

    @ViewInject(R.id.phaseNum)
    private ASView asView;
    @ViewInject(R.id.cb_addition)
    private CheckBox cb_addition;

    @ViewInject(R.id.cb_prizeStop)
    private CheckBox cb_prizeStop;

    @ViewInject(R.id.phase_list)
    private ListView listView;

    @ViewInject(R.id.zhifu_bottom_tv_amount)
    private TextView tv_amount;

    @ViewInject(R.id.zhifu_bottom_tv_balance)
    private TextView tv_balance;

    @ViewInject(R.id.zhifu_bottom_tv_pay)
    private TextView tv_pay;

    private int lotteryId;
    private int zhiuhaoNum = 2;
    private boolean isPrizeStop = false;
    private boolean isAddition = false;
    private int multi;
    private int amt;//单倍彩金
    private String betCode = "";
    private int max_zhuiqi ;


    private List<String> phaseList = new ArrayList<>();
    private List<SeniorPhaseItem> seniorPhaseItems = new ArrayList<>();
    private PhaseListAdapter phaseListAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewCallBack.getInstance().AttachCountDownObj(this);
        lotteryId = getIntent().getIntExtra(IntentParamUtils.LOTTERYID, 0);
        betCode = getIntent().getStringExtra(IntentParamUtils.SENIOR_ZHUIHAO_BETCODE);
        zhiuhaoNum = getIntent().getIntExtra(IntentParamUtils.SENIOR_ZHUIHAO_NUM, 2);
        multi = getIntent().getIntExtra(IntentParamUtils.MULTIPLE, 1);
        max_zhuiqi = getIntent().getIntExtra(IntentParamUtils.AMT_MAXZHUI, 1);
        isPrizeStop = getIntent().getBooleanExtra(IntentParamUtils.SENIOR_ZHUIHAO_PRIZESTOP, false);
        isAddition = getIntent().getBooleanExtra(IntentParamUtils.SENIOR_ZHUIHAO_ADDITION, false);
        amt = getIntent().getIntExtra(IntentParamUtils.AMT, 2);

        tv_balance.setText("彩金:" + MySharedPreferences.getInstance().getBalance() + "米");
        phaseListAdapter = new PhaseListAdapter(this, seniorPhaseItems);
        AmountChangedObserver amountChangedObserver = new AmountChangedObserver();
        phaseListAdapter.registerDataSetObserver(amountChangedObserver);

        if (lotteryId == LotteryIDUtils.DLT_LOTTERY_ID_INT) {
            cb_addition.setChecked(isAddition);
        }
        cb_addition.setOnCheckedChangeListener(onCheckedChangeListener_addition);

        listView.setAdapter(phaseListAdapter);
        cb_prizeStop.setChecked(isPrizeStop);
        asView.setValue(zhiuhaoNum);
        asView.setLeftText("追");
        asView.setRightText("期");
        asView.setMax(max_zhuiqi);
        seniorchase_top.setOnTitleClickListener(this);
        asView.setOnValueChangedLisener(this);
        tv_pay.setOnClickListener(this);
        cb_prizeStop.setOnCheckedChangeListener(onCheckedChangeListener);
        findNextPhaseList();
    }

    @Override
    protected void onDestroy() {
        ViewCallBack.getInstance().DettachCountDownObj(this);
        super.onDestroy();
    }

    CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton
            .OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            isPrizeStop = isChecked;
        }
    };
    CompoundButton.OnCheckedChangeListener onCheckedChangeListener_addition = new CompoundButton
            .OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            isAddition = isChecked;
        }
    };

    @Override
    public void onLeftClick() {
        super.onLeftClick();
    }

    private void findNextPhaseList() {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("lotteryType", lotteryId);
            request_json.put("num", zhiuhaoNum);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpPostJson(CommandUtil.FINDNEXTPHASELIST, Commands.FINDNEXTPHASELIST, request_json,
                true);
    }


    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);

        switch (requestCode) {
            case CommandUtil.FINDNEXTPHASELIST:
                phaseList.clear();
                List<String> phases = JSON.parseArray(resultBean.getData(), String.class);
                for (String phase : phases) {
                    if (phases.indexOf(phase) > seniorPhaseItems.size() - 1) {
                        SeniorPhaseItem item = new SeniorPhaseItem();
                        if (phases.indexOf(phase) == 0) {
                            item.multiple = multi;
                        } else {
                            item.multiple = 1;
                        }
                        if (isAddition) {
                            item.addition = 1;
                        } else {
                            item.addition = 0;
                        }
                        item.phase = phase;
                        item.isSel = true;
                        item.amt = amt;
                        seniorPhaseItems.add(item);
                    }
                }
                int seniorSize = seniorPhaseItems.size();
                int phaseSize = phases.size();
                if (seniorSize > phaseSize) {
                    seniorPhaseItems = seniorPhaseItems.subList(0, phaseSize);
                    phaseListAdapter = new PhaseListAdapter(SeniorZhuiHaoActivity.this,
                            seniorPhaseItems);
                    AmountChangedObserver amountChangedObserver = new AmountChangedObserver();
                    phaseListAdapter.registerDataSetObserver(amountChangedObserver);
                    listView.setAdapter(phaseListAdapter);
                } else {
                    phaseListAdapter.notifyDataSetChanged();
                }
                break;
            case CommandUtil.CHASEBET:

                if (resultBean.getErrorcode().equals("0")) {
                    final String orderId = JSON.parseObject(resultBean.getData(), BetResponse
                            .class).getOrderid();
                    final String lotteryType = lotteryId + "";

                    Intent intent = new Intent();
                    intent.putExtra(IntentParamUtils.SENIOR_ZHUIHAO_ID, orderId);
                    setResult(0, intent);
                    SeniorZhuiHaoActivity.this.finish();

                } else {
                    showToast(resultBean.getMsg());
                }
                break;
        }


    }

    class AmountChangedObserver extends DataSetObserver {

        @Override
        public void onChanged() {
            super.onChanged();
            int value = 0;
            for (SeniorPhaseItem item : seniorPhaseItems) {
                if (item.isSel) {
                    value += item.multiple * item.amt;
                }
            }

            tv_amount.setText("投注总彩金:" + value + "米");
        }

        @Override
        public void onInvalidated() {
            super.onInvalidated();
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.zhifu_bottom_tv_pay:
                int selectCount = 0;
                for (SeniorPhaseItem item : seniorPhaseItems) {
                    if (item.isSel) {
                        selectCount++;
                    }
                }
                if (zhiuhaoNum < 2 || selectCount < 2) {
                    AppToast.getToast().show("至少追2期");
                } else {
                    pay();
                }
                break;
        }
    }


    private void pay() {
        try {
            JSONObject params = new JSONObject();
            params.put("betcode", betCode);
            params.put("lotteryType", lotteryId);
            if (isPrizeStop) {
                params.put("chaseType", 1);
            } else {
                params.put("chaseType", 3);
            }
            if (isAddition) {
                params.put("addition", 1);
            } else {
                params.put("addition", 0);
            }
            params.put("amt", amt * 100);
            params.put("num", seniorPhaseItems.size());
            params.put("multiple", 1);
            params.put("totalPrize", "");
            String beginPhase = "";
            JSONArray jsonArray = new JSONArray();
            for (SeniorPhaseItem item : seniorPhaseItems) {
                if (item.isSel) {
                    if (beginPhase.equals("")) {
                        beginPhase = item.phase;
                    }
                    com.alibaba.fastjson.JSONObject seniorJson = new com.alibaba.fastjson
                            .JSONObject();
                    seniorJson.put("amt", item.amt * 100);
                    seniorJson.put("amount", item.amt * item.multiple * 100);
                    seniorJson.put("phase", item.phase);
                    seniorJson.put("multiple", item.multiple);
                    seniorJson.put("addition", item.addition);
                    LogUtil.v("json" + seniorJson.toString());
                    jsonArray.add(seniorJson);
                }
            }
            params.put("beginPhase", beginPhase);
            LogUtil.v("json" + jsonArray.toString());
            params.put("advancedChase", jsonArray);

            httpPostJson(CommandUtil.CHASEBET, Commands.CHASEBET, params, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 时间截止提示对话框
     */
    public SureDialog endTimeDialog = null;

    @Override
    public void countDown() {
        endTime(lotteryId);
    }

    @Override
    protected void showEndTimeDialog(String period, boolean isShowDialog, int lotteryId) {
        if (isShowDialog && period != null && !period.equals("")) {
            try {
                AppLotteryInfos.period_buffer.append(period + lotteryId);
                new SureDialog(this, new SureDialog.OnDialogOKCancleClickListener() {

                    @Override
                    public void onOKClick() {
                        seniorPhaseItems.clear();
                        findNextPhaseList();
                    }

                    @Override
                    public void onCancleClick() {
                        seniorPhaseItems.clear();
                        findNextPhaseList();
                    }
                }, "" + AppLotteryInfos.getLotteryName(lotteryId), "第" + period + "期已截止！", "确定",
                        "").show();
            } catch (Exception e) {
                L.e(TAG, e.getMessage());
            }
        }
    }

    @Override
    public void onValueChanged(ASView view, int value) {
        this.zhiuhaoNum = value;
        findNextPhaseList();
    }
}
